package LeetCode.month04.day95;

import java.util.*;

/**
 * @author 16778
 * @date 2025/11/4 8:09
 * @description
 */
public class No3318 {
    public int[] findXSum(int[] nums, int k, int x) {
        int n = nums.length;
        int[] res = new int[n - k + 1];
        for (int i = 0; i < n - k + 1; i++) {
            res[i] = get(Arrays.copyOfRange(nums,i,i+k),x);
        }
        return res;
    }

    public int get(int[] arr,int x){
        Arrays.sort(arr);
        int n = arr.length;
        int sum = 0;
        Map<Integer,Integer> map = new TreeMap<>();
        for (int i = 0; i < arr.length; i++) {
            int num = arr[i];
            map.put(arr[i],map.getOrDefault(num,0)+1);
            sum+=arr[i];
        }
        if(map.size()<=x){
            return sum;
        }
        List<Map.Entry<Integer,Integer>> entries = new ArrayList<>(map.entrySet());
        entries.sort((e1,e2)->{
            int valueCompare = e2.getValue().compareTo(e1.getValue());
            if(valueCompare!=0){
                return valueCompare;
            }
            return e2.getKey().compareTo(e1.getKey());
        });

        int count = 0;
        int res = 0;
        for (Map.Entry<Integer, Integer> entry : entries) {
            if(count>=x) break;
            res+=entry.getKey()*entry.getValue();
            count++;
        }
        return res;
    }
}
